package com.zhuiyun.pm.client.bid.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhuiyun.pm.client.action.entity.GoodsEarnestMoneyEntity;
import com.zhuiyun.pm.client.action.entity.GoodsEntity;
import com.zhuiyun.pm.client.action.mapper.GoodsEarnestMoneyMapper;
import com.zhuiyun.pm.client.action.mapper.GoodsMapper;
import com.zhuiyun.pm.client.bid.chat.entity.BidRecord;
import com.zhuiyun.pm.client.bid.chat.entity.OrderInfo;
import com.zhuiyun.pm.client.bid.chat.mapper.BidRecordMapper;
import com.zhuiyun.pm.client.bid.chat.mapper.PcOrderMapper;
import com.zhuiyun.pm.client.bid.chat.service.BidRecordService;
import com.zhuiyun.pm.client.bid.chat.service.WebSocketChatServer;
import com.zhuiyun.pm.client.bid.response.CommonConstants;
import com.zhuiyun.pm.client.bid.util.OrderIdUtil;
import com.zhuiyun.pm.client.login.entity.ClientUser;
import com.zhuiyun.pm.client.login.mapper.UserLoginDao;
import com.zhuiyun.pm.result.CommonResult;
import com.zhuiyun.pm.utils.PrimaryKeyUtil;
import com.zhuiyun.pm.utils.RedisUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName BidRecordServiceImpl
 * @Description TODO
 * @Author lyp
 * @Date 2023/3/15 10:10
 **/
@Service
public class BidRecordServiceImpl implements BidRecordService {

    @Autowired
    BidRecordMapper bidRecordMapper;

    @Autowired
    PcOrderMapper orderMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    UserLoginDao userLoginDao;
    @Autowired
    GoodsEarnestMoneyMapper goodsEarnestMoneyMapper;

    /**
     * 将redis中的拍卖记录存储到redis中 并清理redis中数据
     * @param roomName
     * @return
     */
    @Override
    public CommonResult insertList(String roomName) {
        // 拼接k
//        Object parse = JSON.parse(roomName);
        String BID_RECORD_KEY = CommonConstants.BID_RECORD+roomName;
        List<BidRecord> bidRecordList = (List<BidRecord>)(List)redisUtil.lGet(BID_RECORD_KEY,0,-1);
        if(!CollectionUtils.isEmpty(bidRecordList)){
            // 批量插入数据
            int i = bidRecordMapper.saveBidRecord(bidRecordList);
            // 清除redis中的数据
            if(i==bidRecordList.size()){
                String MAX_PRICE_KEY = CommonConstants.ROOM_AUCTION_PRICE + roomName;
                String MAX_PRICE_USER_KEY =CommonConstants.ROOM_AUCTION_USER+ roomName;
                redisUtil.del(BID_RECORD_KEY);
                // 同时删除其他key
                redisUtil.del(MAX_PRICE_KEY);
                redisUtil.del(MAX_PRICE_USER_KEY);
            }
            return CommonResult.ok(i);
        }
        return CommonResult.error("请联系管理员");
    }

    /**
     * @author lyp
     * @description 拍卖结束生成订单
     * @date 2023/3/20 20:34
     * @param: endOfAuctionInfo
     * @return int
     */
    @Override
    public int saveEndOfAuctionInfo(OrderInfo orderInfo) {
        orderInfo.setOrderFlag(1); // 设置订单为未付款状态
        orderInfo.setDelFlag(0);
        // 生成唯一订单编号
        String strNumber = OrderIdUtil.customFormatDate("yyyyMMddHHmmssSSSSSSS");
        orderInfo.setOrderNumber(strNumber); // 设置订单编号
        orderInfo.setCreationTime(new Date());
        orderInfo.setStrikeTime(new Date()); // 成交时间
        orderInfo.setUpdateTime(new Date()); // 修改时间
        int i = orderMapper.insertSelective(orderInfo);
        return i;
    }

    /**
     * @author lyp
     * @description 根据物品id获取物品信息
     * @date 2023/3/23 19:10
     * @param: id
     * @return GoodsEntity
     */
    @Override
    public GoodsEntity getItemInfoById(Integer id) {
        Example example = new Example(GoodsEntity.class);
        example.createCriteria().andEqualTo("id",id);
        GoodsEntity itemById = goodsMapper.selectOneByExample(example);
        return itemById;
    }
    /**
     * @description:拍卖结束
     * @author: dongdong
     * @date: 2023/4/2 19:54
     * @param: [id]
     * @return: int
    **/
//    @Override
//    public int auctionClose(Integer id) {
//        int i =0;
//
//        synchronized (id){
//            Object o = redisUtil.get(CommonConstants.ROOM_AUCTION_ACQUISITIONS + id);
//            if (o==null){
//                return 1;
//            }
//            redisUtil.del(CommonConstants.ROOM_AUCTION_ACQUISITIONS + id);
//            //最高价用户id
//            Object userId = redisUtil.get(CommonConstants.ROOM_AUCTION_USER + "room" + id);
//            //最高价
//            Object price = redisUtil.get(CommonConstants.ROOM_AUCTION_PRICE + "room" + id);
//            ClientUser clientUser = userLoginDao.selectByPrimaryKey(userId);
//            GoodsEntity goodsEntity = goodsMapper.selectByPrimaryKey(id);
//            OrderInfo orderInfo = new OrderInfo();
//            orderInfo.setOrderFlag(1); // 设置订单为未付款状态
//            orderInfo.setDelFlag(0);
//            orderInfo.setTransactionPrice( ((Double)price).intValue());
//            orderInfo.setBidder( Integer.valueOf( userId.toString()));
//            orderInfo.setProductId(id);
//            orderInfo.setStartingPrice(Integer.valueOf(goodsEntity.getStartPrice()));
//            // 生成唯一订单编号
//            String strNumber = OrderIdUtil.customFormatDate("yyyyMMddHHmmssSSSSSSS");
//            orderInfo.setOrderNumber(strNumber); // 设置订单编号
//            orderInfo.setCreationTime(new Date());
//            orderInfo.setStrikeTime(new Date()); // 成交时间
//            orderInfo.setUpdateTime(new Date()); // 修改时间
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("type","auctionClose");
//            jsonObject.put("userName",clientUser.getUserName());
//            jsonObject.put("price",price);
//            GoodsEarnestMoneyEntity goodsEarnestMoneyEntity = new GoodsEarnestMoneyEntity();
//            goodsEarnestMoneyEntity.setTransactionStatus(1);
//            Example example = new Example(GoodsEarnestMoneyEntity.class);
//            example.createCriteria().andEqualTo("userId",userId).andEqualTo("goodsId",id);
//
//            goodsEarnestMoneyMapper.updateByExampleSelective(goodsEarnestMoneyEntity,example);
//            try {
//                WebSocketChatServer.sendRoomMsg("room"+id,jsonObject.toString());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            i = orderMapper.insertSelective(orderInfo);
//        }
//        return i;
//    }
}
